package com.yunma.dialog;

import com.common.bean.RequestInfoBean;
import com.common.bean.RequestParameterTemplate;
import com.common.util.WindowUtil;
import com.string.widget.util.ValueWidget;
import com.swing.component.AssistPopupTextField;
import com.swing.component.ComponentUtil;
import com.swing.component.MyNamePanel;
import com.swing.dialog.DialogUtil;
import com.swing.dialog.GenericDialog;
import com.swing.dialog.toast.ToastMessage;
import com.swing.menu.MenuUtil2;
import com.yunma.autotest.RequestPanel;
import com.yunma.bean.ComboBoxItemBean;
import com.yunma.component.ParameterPanel;
import com.yunma.util.TableUtil;
import org.apache.commons.collections.map.ListOrderedMap;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;

public class AddOptionalParametersDialog extends GenericDialog implements ItemListener {

    private static final long serialVersionUID = -396038300996724169L;
    private final JPanel panel_1;
    private JPanel contentPane;
    private AssistPopupTextField searchTextField;
    private AssistPopupTextField displaynameTextField;
    private java.util.List<ParameterPanel> parameterPanels = new ArrayList();
    private JTabbedPane tabbedPane;
    private JComboBox<Object> requestComboBox;
    private JComboBox<Object> displayNameComboBox;
    private java.util.List<RequestParameterTemplate> requestParameterTemplates;
    /**
     * 增加item触发了itemStateChanged事件
     */
    private boolean notItemStateChanged = false;
    /***
     * 是否立即发送请求<br />
     * 存储到什么地方呢?<br />
     * RequestPanel的成员变量OriginalRequestInfoBean 中
     */
    private JCheckBox sendNowCheckBox;
    private AssistPopupTextField serverIPtextField;

    /**
     * Launch the application.
     */
    /*public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    AddOptionalParametersDialog frame = new AddOptionalParametersDialog(null);
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }*/

    /**
     * Create the frame.
     */
    public AddOptionalParametersDialog(final JTabbedPane tabbedPane) {
        this.tabbedPane = tabbedPane;
        this.setTitle("添加请求参数模板");
        setModal(true);
//	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLoc(550, 400);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.CENTER);
        GridBagLayout gbl_panel = new GridBagLayout();
        gbl_panel.columnWidths = new int[]{0, 0, 0, 0};
        gbl_panel.rowHeights = new int[]{0, 50, 0, 0, 0, 0, 0, 0, 0, 0};
        gbl_panel.columnWeights = new double[]{0.0, 0.0, 1.0, Double.MIN_VALUE};
        gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
        panel.setLayout(gbl_panel);

        JLabel label = new JLabel("选择请求");
        label.setBackground(Color.PINK);
        GridBagConstraints gbc_label = new GridBagConstraints();
        gbc_label.anchor = GridBagConstraints.WEST;
        gbc_label.insets = new Insets(0, 0, 5, 5);
        gbc_label.gridx = 0;
        gbc_label.gridy = 0;
        panel.add(label, gbc_label);

        searchTextField = new AssistPopupTextField();
        RequestPanel requestPanel = (RequestPanel) tabbedPane.getSelectedComponent();
        searchTextField.setText(requestPanel.getRequestName());
        searchTextField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                searchAction(tabbedPane);
            }
        });
        searchTextField.addFocusListener(new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent e) {
                super.focusLost(e);
                if (0 == requestComboBox.getItemCount()) {//"选择请求"文本框失去焦点时触发搜索,但是只有当"选择请求"下拉框为空时才搜索
                    setNotItemStateChanged(true);
                    searchAction(tabbedPane);
                    setNotItemStateChanged(false);
                }
            }
        });
        GridBagConstraints gbc_searchTextField = new GridBagConstraints();
        gbc_searchTextField.insets = new Insets(0, 0, 5, 0);
        gbc_searchTextField.fill = GridBagConstraints.HORIZONTAL;
        gbc_searchTextField.gridx = 2;
        gbc_searchTextField.gridy = 0;
        panel.add(searchTextField, gbc_searchTextField);
        searchTextField.setColumns(10);

        requestComboBox = new JComboBox<Object>();
        requestComboBox.addItemListener(this);//见本类的 itemStateChanged 方法

        JComboBox requestOpratComboBox = new JComboBox();
        GridBagConstraints gbc_requestOpratComboBox = new GridBagConstraints();
        gbc_requestOpratComboBox.anchor = GridBagConstraints.NORTH;
        gbc_requestOpratComboBox.insets = new Insets(0, 0, 5, 5);
        gbc_requestOpratComboBox.fill = GridBagConstraints.HORIZONTAL;
        gbc_requestOpratComboBox.gridx = 0;
        gbc_requestOpratComboBox.gridy = 1;
        panel.add(requestOpratComboBox, gbc_requestOpratComboBox);
        requestComboBox.setBackground(Color.PINK);
        GridBagConstraints gbc_requestComboBox = new GridBagConstraints();
        gbc_requestComboBox.anchor = GridBagConstraints.NORTH;
        gbc_requestComboBox.insets = new Insets(0, 0, 5, 0);
        gbc_requestComboBox.fill = GridBagConstraints.HORIZONTAL;
        gbc_requestComboBox.gridx = 2;
        gbc_requestComboBox.gridy = 1;
        panel.add(requestComboBox, gbc_requestComboBox);

        JLabel label_1 = new JLabel("参数显示名称");
        GridBagConstraints gbc_label_1 = new GridBagConstraints();
        gbc_label_1.anchor = GridBagConstraints.WEST;
        gbc_label_1.insets = new Insets(0, 0, 5, 5);
        gbc_label_1.gridx = 0;
        gbc_label_1.gridy = 2;
        panel.add(label_1, gbc_label_1);

        displaynameTextField = new AssistPopupTextField();
        GridBagConstraints gbc_displaynameTextField = new GridBagConstraints();
        gbc_displaynameTextField.insets = new Insets(0, 0, 5, 0);
        gbc_displaynameTextField.fill = GridBagConstraints.HORIZONTAL;
        gbc_displaynameTextField.gridx = 2;
        gbc_displaynameTextField.gridy = 2;
        panel.add(displaynameTextField, gbc_displaynameTextField);
        displaynameTextField.setColumns(10);
        displaynameTextField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                optionalParametersAction();
            }
        });
        displaynameTextField.addFocusListener(new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent e) {
                super.focusLost(e);
                if (0 == displayNameComboBox.getItemCount()) {
                    optionalParametersAction();
                }
            }

            @Override
            public void focusGained(FocusEvent e) {
                super.focusGained(e);
                if (0 == requestComboBox.getItemCount()) {
                    ToastMessage.toast("请选择请求", 2000, Color.red);
                    searchAction(tabbedPane);//展示请求面板下拉框
                }
            }
        });

        displayNameComboBox = new JComboBox<Object>();
        displayNameComboBox.addItemListener(this);//见本类的 itemStateChanged 方法
        displayNameComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                displayComboAction();
            }
        });

        JComboBox parameterOperatComboBox = new JComboBox();
        GridBagConstraints gbc_parameterOperatComboBox = new GridBagConstraints();
        gbc_parameterOperatComboBox.anchor = GridBagConstraints.NORTH;
        gbc_parameterOperatComboBox.insets = new Insets(0, 0, 5, 5);
        gbc_parameterOperatComboBox.fill = GridBagConstraints.HORIZONTAL;
        gbc_parameterOperatComboBox.gridx = 0;
        gbc_parameterOperatComboBox.gridy = 3;
        panel.add(parameterOperatComboBox, gbc_parameterOperatComboBox);
        GridBagConstraints gbc_displayNameComboBox = new GridBagConstraints();
        gbc_displayNameComboBox.anchor = GridBagConstraints.NORTH;
        gbc_displayNameComboBox.insets = new Insets(0, 0, 5, 0);
        gbc_displayNameComboBox.fill = GridBagConstraints.HORIZONTAL;
        gbc_displayNameComboBox.gridx = 2;
        gbc_displayNameComboBox.gridy = 3;
        panel.add(displayNameComboBox, gbc_displayNameComboBox);

        JLabel lblip = new JLabel("服务器ip");
        GridBagConstraints gbc_lblip = new GridBagConstraints();
        gbc_lblip.anchor = GridBagConstraints.WEST;
        gbc_lblip.insets = new Insets(0, 0, 5, 5);
        gbc_lblip.gridx = 0;
        gbc_lblip.gridy = 4;
        panel.add(lblip, gbc_lblip);

        serverIPtextField = new AssistPopupTextField();
        GridBagConstraints gbc_serverIPtextField = new GridBagConstraints();
        gbc_serverIPtextField.insets = new Insets(0, 0, 5, 0);
        gbc_serverIPtextField.fill = GridBagConstraints.HORIZONTAL;
        gbc_serverIPtextField.gridx = 2;
        gbc_serverIPtextField.gridy = 4;
        panel.add(serverIPtextField, gbc_serverIPtextField);
        serverIPtextField.setColumns(10);

        JPanel panel_5 = new JPanel();
        GridBagConstraints gbc_panel_5 = new GridBagConstraints();
        gbc_panel_5.anchor = GridBagConstraints.WEST;
        gbc_panel_5.gridwidth = 3;
        gbc_panel_5.insets = new Insets(0, 0, 5, 0);
        gbc_panel_5.fill = GridBagConstraints.VERTICAL;
        gbc_panel_5.gridx = 0;
        gbc_panel_5.gridy = 5;
        panel.add(panel_5, gbc_panel_5);

        sendNowCheckBox = new JCheckBox("切换时即发送请求");
        RequestInfoBean requestInfoBean = requestPanel.getOriginalRequestInfoBean();
        if (null != requestInfoBean) {
            sendNowCheckBox.setSelected(requestInfoBean.isSendRightNow());
        }

        panel_5.add(sendNowCheckBox);

        JPanel panel_4 = new JPanel();
        GridBagConstraints gbc_panel_4 = new GridBagConstraints();
        gbc_panel_4.gridwidth = 3;
        gbc_panel_4.insets = new Insets(0, 0, 5, 0);
        gbc_panel_4.fill = GridBagConstraints.BOTH;
        gbc_panel_4.gridx = 0;
        gbc_panel_4.gridy = 6;
        panel.add(panel_4, gbc_panel_4);

        JButton cleanUpParameterButton = new JButton("清空下面参数");
        cleanUpParameterButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                TableUtil.cleanUpParameterpanel(parameterPanels);
            }
        });
        panel_4.add(cleanUpParameterButton);

        JButton btnCopyJson = new JButton("复制参数为json");
        btnCopyJson.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ListOrderedMap parameters = TableUtil.getParameterOrderedMap(parameterPanels);
                if (parameters == null) return;
                WindowUtil.setSysClipboardText(parameters.toString());
            }
        });
        panel_4.add(btnCopyJson);

        JScrollPane scrollPane = new JScrollPane();
        GridBagConstraints gbc_scrollPane = new GridBagConstraints();
        gbc_scrollPane.insets = new Insets(0, 0, 5, 0);
        gbc_scrollPane.gridwidth = 3;
        gbc_scrollPane.fill = GridBagConstraints.BOTH;
        gbc_scrollPane.gridx = 0;
        gbc_scrollPane.gridy = 7;
        panel.add(scrollPane, gbc_scrollPane);

        panel_1 = new JPanel();
        scrollPane.setViewportView(panel_1);
        panel_1.setLayout(new GridLayout(10, 1, 0, 0));


        ParameterPanel panel_2 = new ParameterPanel();
        panel_2.layout2();
        parameterPanels.add(panel_2);
        panel_1.add(panel_2);


        JPanel panel_3 = new JPanel();
        GridBagConstraints gbc_panel_3 = new GridBagConstraints();
        gbc_panel_3.gridwidth = 3;
        gbc_panel_3.fill = GridBagConstraints.BOTH;
        gbc_panel_3.gridx = 0;
        gbc_panel_3.gridy = 8;
        panel.add(panel_3, gbc_panel_3);

        JButton addRowButton = new JButton("添加一行");
        addRowButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("添加一行");
                ParameterPanel panel_3222 = new ParameterPanel();
                panel_3222.layout2();
                TableUtil.addOptionalParameterPanel(panel_3222, panel_1, parameterPanels);
                panel_1.updateUI();
            }
        });
        panel_3.add(addRowButton);

        JButton btnSave = new JButton("save");
        btnSave.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                save(tabbedPane, false);
            }
        });
        panel_3.add(btnSave);

        JButton btnAdd = new JButton("add");
        btnAdd.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                save(tabbedPane, true);
            }
        });
        panel_3.add(btnAdd);

        JButton btnClose = new JButton("cancel");
        btnClose.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                AddOptionalParametersDialog.this.dispose();
            }
        });
        panel_3.add(btnClose);

        searchAction(tabbedPane);
        DialogUtil.escape2CloseDialog(this);
    }

    public void save(JTabbedPane tabbedPane, boolean isAdd) {
        ListOrderedMap parameters = TableUtil.getParameterOrderedMap(parameterPanels);
        if (parameters == null) return;
        RequestPanel requestPanel = getRequestPanel(tabbedPane);
        System.out.println(requestPanel.getRequestName());
        RequestParameterTemplate requestParameterTemplate = new RequestParameterTemplate();
        requestParameterTemplate.setDisplayName(displaynameTextField.getText2());
        requestParameterTemplate.setServerIp(serverIPtextField.getText2());
        requestParameterTemplate.setParameters(parameters);
        List<RequestParameterTemplate> oldRequestParameterTemplates = getRequestParameterTemplates(requestPanel);
/*List oldRequestParameterTemplates = requestPanel.getRequestParameterTemplates();
if(null==oldRequestParameterTemplates){
oldRequestParameterTemplates=requestPanel.getOriginalRequestInfoBean().getRequestParameterTemplates();
}*/

        oldRequestParameterTemplates = updateRequestParameterTemplates(parameters, requestParameterTemplate, oldRequestParameterTemplates, isAdd);
// List<RequestParameterTemplate> requestParameterTemplates = new ArrayList();

        requestPanel.setRequestParameterTemplates(oldRequestParameterTemplates);
//因为保存时requestPanel.isAlreadyRended2() 为false时,会保存requestPanel.getOriginalRequestInfoBean()
        requestPanel.getOriginalRequestInfoBean().setRequestParameterTemplates(oldRequestParameterTemplates);
        requestPanel.setSendRightNow(sendNowCheckBox.isSelected());
        AddOptionalParametersDialog.this.dispose();//点击"save"和"add"之后,建议不要关闭窗口,因为用户可能连续添加
        ToastMessage.toast("操作成功", 2000);
    }


    public List<RequestParameterTemplate> updateRequestParameterTemplates(ListOrderedMap parameters, RequestParameterTemplate requestParameterTemplate, List oldRequestParameterTemplates, boolean isAdd) {
        boolean isEmpty = false;
        if (oldRequestParameterTemplates == null) {
            isEmpty = true;
            oldRequestParameterTemplates = new ArrayList<RequestParameterTemplate>();
        } else if (ValueWidget.isNullOrEmpty(oldRequestParameterTemplates)) {
            isEmpty = true;
        }
        if (isEmpty) {
            oldRequestParameterTemplates.add(requestParameterTemplate);
        } else {
            int size2 = oldRequestParameterTemplates.size();
            ComboBoxItemBean comboBoxItemBean = (ComboBoxItemBean) displayNameComboBox.getSelectedItem();
            String displayName = null;
            if (isAdd) {
                displayName = displaynameTextField.getText2();
            } else {
                displayName = comboBoxItemBean.getDisplayName();
            }
            if (ValueWidget.isNullOrEmpty(displayName)) {//"参数显示名称"文本框为空的时候
                displayName = comboBoxItemBean.getDisplayName();
            }
            boolean hasFound = false;
            for (int i = 0; i < size2; i++) {
                RequestParameterTemplate requestParameterTemplate1 = (RequestParameterTemplate) oldRequestParameterTemplates.get(i);
                if (requestParameterTemplate1.getDisplayName().equals(displayName)) {
                    hasFound = true;
                    //保存时更新
                    requestParameterTemplate1.setParameters(parameters);
                    requestParameterTemplate1.setServerIp(requestParameterTemplate.getServerIp());
                }
            }
            if (!hasFound) {
                oldRequestParameterTemplates.add(requestParameterTemplate);
            }
        }
        return oldRequestParameterTemplates;
    }

    public RequestPanel getRequestPanel(JTabbedPane tabbedPane) {
        ComboBoxItemBean comboBoxItemBean = (ComboBoxItemBean) requestComboBox.getItemAt(requestComboBox.getSelectedIndex());
        if (null == comboBoxItemBean) {
            System.out.println("select comboBoxItemBean is null");
            return null;
        }
        int tabSelectedIndex = comboBoxItemBean.getIndex();
        System.out.println("selected index:" + tabSelectedIndex);
        return (RequestPanel) tabbedPane.getComponentAt(tabSelectedIndex);
    }

    public void searchAction(JTabbedPane tabbedPane) {
        Set<Integer> searchResult = MenuUtil2.searchAction(searchTextField.getText2(), tabbedPane, true/*includeActionName*/);
        if (null == searchResult) return;
        List<ComboBoxItemBean> items = new ArrayList<ComboBoxItemBean>();
        for (Iterator<Integer> it = searchResult.iterator(); it.hasNext(); ) {
            int select = (Integer) it.next();
            Component comp = tabbedPane.getComponentAt(select);
            if (comp instanceof MyNamePanel) {
                MyNamePanel requestPanel = (MyNamePanel) comp;
                String requestName = requestPanel.getRequestName();
                if (ValueWidget.isNullOrEmpty(requestName)) {
                    requestName = String.valueOf(select);
                } else {
                    requestName = requestName + "(" + select + ")";
                }
                items.add(new ComboBoxItemBean(requestName, select));
//	textPopupMenu.addSeparator();
            }
        }
        if (requestComboBox.getItemCount() > 0) {
            requestComboBox.removeAllItems();
        }
        ComponentUtil.fillComboBox(requestComboBox, items.toArray());
    }

    public void optionalParametersAction() {
        RequestPanel currentRequestPanel = getRequestPanel(tabbedPane);
        if (null == currentRequestPanel) {
            System.out.println("optionalParametersAction 没有找到RequestPanel");
            return;
        }
        requestParameterTemplates = getRequestParameterTemplates(currentRequestPanel);
        if (ValueWidget.isNullOrEmpty(requestParameterTemplates)) {
            System.out.println("没有可选的参数");
            removeDisplayNameAllItems();
            return;
        }
        int size = requestParameterTemplates.size();
        List<ComboBoxItemBean> items = new ArrayList<ComboBoxItemBean>();
        String inputDisplayName = displaynameTextField.getText2();
        for (int i = 0; i < size; i++) {
            String displayName = ((RequestParameterTemplate) requestParameterTemplates.get(i)).getDisplayName();
            if (ValueWidget.isNullOrEmpty(inputDisplayName) || displayName.contains(inputDisplayName)) {
                items.add(new ComboBoxItemBean(displayName, i));
            }
        }
        removeDisplayNameAllItems();
        ComponentUtil.fillComboBox(displayNameComboBox, items.toArray());
    }

    public void removeDisplayNameAllItems() {
        if (displayNameComboBox.getItemCount() > 0) {
            displayNameComboBox.removeAllItems();
        }
    }

    public List<RequestParameterTemplate> getRequestParameterTemplates(RequestPanel currentRequestPanel) {
        List<RequestParameterTemplate> requestParameterTemplates = currentRequestPanel.getRequestParameterTemplates();
        if (null == requestParameterTemplates && !ValueWidget.isNullOrEmpty(currentRequestPanel.getOriginalRequestInfoBean())) {
            requestParameterTemplates = currentRequestPanel.getOriginalRequestInfoBean().getRequestParameterTemplates();
        }
        return requestParameterTemplates;
    }


    @Override
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            if (e.getSource() == requestComboBox) {//"选择请求"下拉框
                if (!isNotItemStateChanged()) {
                    TableUtil.cleanUpParameterpanel(parameterPanels);
                }
                optionalParametersAction();
            } else {//"参数显示名称"下拉框
// System.out.println(e);
                JComboBox combo = (JComboBox) e.getSource();
// System.out.println(combo.getSelectedItem());
// System.out.println("\"参数显示名称\"下拉框");
                displayComboAction();
            }
        }


    }

    public void displayComboAction() {
        ComboBoxItemBean comboBoxItemBean = (ComboBoxItemBean) displayNameComboBox.getItemAt(displayNameComboBox.getSelectedIndex());
        if (null == comboBoxItemBean) {
            System.out.println("select displayNameComboBox is null");
            return;
        }
// displaynameTextField.setText(comboBoxItemBean.getDisplayName());
        int tabSelectedIndex = comboBoxItemBean.getIndex();
        RequestParameterTemplate requestParameterTemplate = (RequestParameterTemplate) this.requestParameterTemplates.get(tabSelectedIndex);
        Map<String, String> parameters = requestParameterTemplate.getParameters();
        TableUtil.initParameterPanel(parameters, panel_1, parameterPanels);
        serverIPtextField.setText(requestParameterTemplate.getServerIp());
    }


    public synchronized boolean isNotItemStateChanged() {
        return notItemStateChanged;
    }

    public synchronized void setNotItemStateChanged(boolean notItemStateChanged) {
        this.notItemStateChanged = notItemStateChanged;
    }
}